// Project adapted from https://developer.nvidia.com/blog/even-easier-introduction-cuda/

#include <iostream>
#include <math.h> // for fmax() and fabs()

// function to add the elements of two arrays
void vector_add(int array_size, float *x, float *y, float *z)
{
    for (int i = 0; i < array_size; i++)
        z[i] = x[i] + y[i];
}

int main(void)
{
    int array_size = 1<<20; // 1 M elements
    float *x, *y, *z;
    x = (float*)malloc(array_size*sizeof(float));
    y = (float*)malloc(array_size*sizeof(float));
    z = (float*)malloc(array_size*sizeof(float));

    // initialize x and y arrays on the host
    for (int i = 0; i < array_size; i++) {
        x[i] = 1.0f;
        y[i] = 2.0f;
    }

    // Run kernel on 1M elements on the CPU
    vector_add(array_size, x, y, z);

    //检验是否所有的结果都是3.0f。
    std::cout << "z[0]: " << z[0] << std::endl;
    float maxError = 0.0f;
    for (int i = 0; i < array_size; i++)
        maxError = fmax(maxError, fabs(z[i]-3.0f));
    if(maxError < 1e-6)
        std::cout << "PASS: Max error: " << maxError << std::endl;
    else
        std::cout << "FAIL: Max error: " << maxError << std::endl;

    // Free memory
    free(x);
    free(y);
    free(z);
    return 0;
}